import React, { Component } from 'react';
import CommonHeader from '../common/jsx/common_header';
import style from './modify.module.css';
import $ from 'jquery';
import ModifyMain from './modify-main/modify-main';
import { Layout, Input,Upload, Icon, Modal,Select,Cascader,DatePicker,Radio } from 'antd';
import Ueditor from './ueditor/ueditor';
import moment from 'moment';
const { Header, Footer, Sider, Content } = Layout;
const { MonthPicker, RangePicker, WeekPicker } = DatePicker;
const { Option } = Select;
const { TextArea } = Input;

function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
  });
}

function img_getBase64(img, callback) {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result));
  reader.readAsDataURL(img);
}

function downloadIamge(imgsrc, name) {//下载图片地址和图片名
  let image = new Image();
  // 解决跨域 Canvas 污染问题
  image.setAttribute("crossOrigin", "anonymous");
  image.onload = function() {
    let canvas = document.createElement("canvas");
    canvas.width = image.width;
    canvas.height = image.height;
    let context = canvas.getContext("2d");
    context.drawImage(image, 0, 0, image.width, image.height);
    let url = canvas.toDataURL("image/png"); //得到图片的base64编码数据
    let a = document.createElement("a"); // 生成一个a元素
    let event = new MouseEvent("click"); // 创建一个单击事件
    a.download = name || "photo"; // 设置图片名称
    a.href = url; // 将生成的URL设置为a.href属性
    a.dispatchEvent(event); // 触发a的单击事件
  };
  image.src = imgsrc;
}

class Modify extends Component {
  constructor(props) {
    super(props);
  }

  state = {
    bread:[
      {name:'返回上级',url:'',ifback:true},
      {name:'修改信息',url:'',p_bread:true}
    ],
    title_name:'修改信息',
    data:[],
    header_idx:0,
    previewVisible: false,
    previewImage: '',
    fileList: [],
    status:1, 
    id:'myeditor',
    ueditor:null,
    DatePickerMod:'time',
    title:'',  //标题名
    value:'',  //富文本内容
    label:'',  //标签
    imgurl:[], //细节图
    listimgurl:'',//列表图
    updatatime:'',//更新时间
    updata_timestamp:'',//时间戳
    downloadimg:'', //下载图片地址
    sectionarr:'', //栏目
    sectionid:'', //栏目id
    sectionname:'',//栏目名
    lanmu_options:[], //所有栏目
    orders:'', //排序
    ifdisplay:"1", //是否显示
  }

  componentDidMount() {
    console.log(this.props)
    let UE = window.UE;
    let {id} = this.state;
    const that = this
    if(id){
      try {
        /*加载之前先执行删除操作，否则如果存在页面切换，
        再切回带编辑器页面重新加载时不刷新无法渲染出编辑器*/
        UE.delEditor(id);
      }catch (e) {}
      let ueditor = UE.getEditor(id, {
        autoHeightEnabled: false,
        autoFloatEnabled: true
      });
      this.setState({ueditor});
      ueditor.addListener('selectionchange',function(type, arg1, arg2){   //addListener监听事件，selectionchange输入框改变事件
        that.setState({
          value:ueditor.getContent()
        })
      })
    }
    //请求数据
    if(this.props.match.params.act == "modify"){
      $.ajax({
        url:`/${this.props.match.params.url}`,
        type:'GET',
        data:{
          id:this.props.match.params.id,
          act:'detail_list',
        },
        dataType:'json',
        success(obj){
          // console.log(obj)
          let e = obj.data;
          let fileList = [];
          if(e.detailimg!=""){   //生成初始细节图
            for(let i in e.detailimg){   
              fileList[i]={
                uid: `-${i}`,
                response:{status:'done',imgurl:e.detailimg[i]},
                url: e.detailimg[i],
                thumbUrl:e.detailimg[i],
                status:'done',
              }
            }
            that.setState({
              fileList
            })
          }
          // console.log(e.updatatime)
          that.setState({
            title:e.name,
            updatatime:that.changetime(e.updatatime),
            listimgurl:e.listimg,
            orders:e.orders,
            ifdisplay:e.ifdisplay,
            sectionid:e.section,
            sectionname:e.sectionname,
            data:e,
          })
          that.getallsection(e.psection,e.section)
        }
      })
    }else{
      that.getallsection(this.props.match.params.id)
    }
  }

  headerClick(idx,mod){
    this.setState({
      header_idx:idx
    })
  }

  handleCancel = () => this.setState({ previewVisible: false });

  handlePreview = async file => {
    console.log(file)
    if (!file.url && !file.preview) {
      file.preview = await getBase64(file.originFileObj);
    }

    this.setState({
      previewImage: file.url || file.preview,
      previewVisible: true,
    });
  };

  handleChange = ({ fileList }) => {
    console.log(fileList)
    const that = this;
    //let imgurls = this.state.imgurl;   //如果你直接用imgurls去push数组，会改变this.state.imgurl中的值，相当于imgurls定位了this.state.imgurl的地址
    let imgurl = [];
    // console.log(fileList.filter(e=>(e.response != undefined)).length == fileList.length)
    if(fileList.filter(e=>(e.response != undefined)).length == fileList.length){
      // imgurl = imgurl.concat(imgurls)
      for(let obj of fileList){
        if(obj.response.status == 'done'){
          imgurl.push(obj.response.imgurl)
        }
      }
      // console.log(imgurl,fileList)
      // $.ajax({
      //   url:"/product",
      //   type:'GET',
      //   dataType:'json',
      //   data:{
      //     id:this.props.match.params.id,
      //     act:'xijie_img',
      //     imgurl,
      //   },  
      //   success(e){
      //     if(e.status != 1){
      //       alert(e.msg)
      //     }
      //   }
      // })
    }
    console.log(imgurl)
    this.setState({ imgurl,fileList })
  };

  imghandleChange = info => {    //列表图变换触发事件
    // console.log(info.file.response != undefined)
    const that = this;
    let listimgurl = [];
    if(info.file.response != undefined){
      listimgurl=info.file.response.imgurl
      this.setState({
        listimgurl,
      })
    }
    // Get this url from response in real world.
    // img_getBase64(info.file.originFileObj, listimgurl =>
    //   this.setState({
    //     listimgurl,
    //   }),
    // );
  };

  handleDownload=(e)=>{  //点击下载
    // console.log(e,$('#downloadimg_a'))
    // downloadIamge(e.url)
    this.setState({
      downloadimg:e.url,
    })
    $('#downloadimg_a')[0].click()
  }

  datechange=(date,dateString)=>{ //改变时间
    console.log(date,dateString)
    this.setState({
      updatatime:dateString.replace(/ ,-,:/g,''),
      updata_timestamp:Date.parse(new Date(dateString))/1000
    })
  }

  getsecname=(section,allsection)=>{ //获取栏目
    // console.log(section,allsection)
    const that = this;
    let name = '';
    let pname = '';
    let sectionarr = []
    if(section!=-1){
      for(let i of allsection){
        if(i.id != section){
          if(i.children){
            for(let j of i.children){
              if(j.id == section){
                name = j.name
                pname = i.name
              }
            }
          }
        }else{
          name = i.name
        }
      }
      if(pname!=''){
        sectionarr = [pname,name]
      }else{
        sectionarr = [name]
      }
      // console.log(sectionarr)
      this.setState({
        sectionarr
      })
    }
  }

  getallsection=(pid,id)=>{  //获取所有栏目
    // console.log(id)
    const that = this;
    $.ajax({
      url:`/${this.props.match.params.url}`,
      type:'GET',
      data:{
        act:'proSection',
        id:pid
      },
      dataType:'json',
      success(obj){
        let e = obj.data
        let arr = []
        let sectionarr = []
        for(let s of e){
          s.label = s.name
          if(s.id == id){
            sectionarr = [s.name]
          }
        }
        for(let i of e.filter(obj=>obj.pid == pid&&obj.id != -1)){
          if(e.filter(obj=>obj.pid == i.id).length != 0){
            i.children = e.filter(obj=>obj.pid == i.id)
          }
          arr.push(i)
        }
        if(that.props.match.params.act == "modify"){
          that.getsecname(id,arr)
        }
        that.setState({
          lanmu_options:arr,
        })
      }
    })
  }



  release=()=>{  //发布
    // console.log(this.state)
    const that = this
    $.ajax({
      url:`/${this.props.match.params.url}`,
      type:'GET',
      data:{
        id:this.props.match.params.id,
        act:`${that.props.match.params.act == "modify"?'submit':'add'}`,
        release:'yes',
        title:this.state.title,
        section:this.state.sectionid,
        sectionname:this.state.sectionname,
        ifdisplay:this.state.ifdisplay,
        orders:this.state.orders,
        listimg:this.state.listimgurl,
        detailimg:this.state.imgurl,
        updatatime:this.state.updata_timestamp!=''?this.state.updata_timestamp:Math.round(new Date() / 1000),
      },
      dataType:'json',
      success(e){
        // console.log(e)
        alert(e.msg)
        if(e.status == 1){
          that.props.history.goBack()
        }
      }
    })
  }

  statusChange = e => {  //显示隐藏改变事件
    this.setState({
      ifdisplay: e.target.value,
    });
  };

  inputChangeName=(e)=>{
    this.setState({
      title:e.target.value
    })
  }

  inputChangeLabel=(e)=>{
    this.setState({
      label:e.target.value
    })
  }
  
  goback=()=>{
    this.props.history.goBack()
  }

  changetime=(ntime)=>{
    // console.log(ntime)
    if(ntime.length<=10){
      var time = new Date(parseInt(ntime)*1000)
    }else{
      var time = new Date(ntime)
    }
    // console.log(''+time.getFullYear()+((time.getMonth()+1)<10?('0'+(time.getMonth()+1)):(time.getMonth()+1))+time.getDate()+time.getHours()+(time.getMinutes()<10?('0'+time.getMinutes()):time.getMinutes())+time.getSeconds())
    return (''+time.getFullYear()+((time.getMonth()+1)<10?('0'+(time.getMonth()+1)):(time.getMonth()+1))+(time.getDate()<10?'0'+time.getDate():time.getDate())+(time.getHours()<10?'0'+time.getHours():time.getHours())+(time.getMinutes()<10?('0'+time.getMinutes()):time.getMinutes())+time.getSeconds());
  }

  handleOpenChange = open => {
    if (open) {
      this.setState({ DatePickerMod: 'time' });
    }
  };

  handlePanelChange = (value, mode) => {
    this.setState({ DatePickerMod:mode });
  };
 
  cascaderChange = (value,selectedOptions)=>{  //选择栏目change事件
    // console.log(value,selectedOptions)
    let sectionid = selectedOptions.find(e=>!e.children).id
    // console.log(sectionid)
    this.setState({
      sectionarr:value,
      sectionname:value[value.length-1],
      sectionid
    })
  } 

  orderChange=(e)=>{  //排序改变事件
    // console.log(e.target.value)
    this.setState({
      orders:e.target.value
    })
  }

  render() { 
    const { previewVisible, previewImage,fileList,listimgurl } = this.state;
    const uploadButton = (
      <div>
        <Icon type="plus" />
        <div className="ant-upload-text">上传图片</div>
      </div>
    );

    return (
      <div>
        <CommonHeader goback={this.goback} bread={this.state.bread} title_name={this.state.title_name} />
        <div className={style.main}>
          <ul className={style.main_header}>
            <li className={this.state.header_idx==0?style.main_header_act:''} onClick={this.headerClick.bind(this,0,'base')}>基本信息</li>
            <li className={this.state.header_idx==1?style.main_header_act:''} onClick={this.headerClick.bind(this,1,'seo')}>SEO设置</li>
          </ul>
          <div style={this.state.header_idx == 0?{display:'block'}:{display:'none'}} className={style.content}>
            <Layout>
              <Content className={style.content_center}>
                <div className={style.contentlist}>
                  <span>标题：</span>
                  <Input placeholder='输入您的标题' value={this.state.title} onChange={this.inputChangeName.bind(this)}/>
                </div>
                <div className={style.contentlist02}>
                  <span>修改内容：</span>
                  {/* <Ueditor className={style.myeditor} id={'myeditor'} /> */
                   <div className={style.myeditor} id={this.state.id}></div>}
                </div>
                <div className={style.contentlist03}>
                  <span>标签：</span>
                  <Input className={style.contentlist03_input} placeholder='输入您的标签' onChange={this.inputChangeLabel.bind(this)} />
                </div>
                <div className={style.contentlist02}>
                  <span>细节图：</span>
                  <a href="/upload/image/碎片表.png" target='_blank' download="" id='downloadimg_a' className={style.downloadimg_a}></a>
                  <div className="clearfix">
                    <Upload
                      action="/upload"
                      // action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
                      listType="picture-card"
                      fileList={fileList}
                      onPreview={this.handlePreview}   //	点击文件链接或预览图标时的回调
                      onDownload={this.handleDownload}
                      onChange={this.handleChange}     // 上传文件改变时的状态
                    >
                      {fileList.length >= 8 ? null : uploadButton}
                      
                    </Upload>
                    <Modal visible={previewVisible} footer={null} onCancel={this.handleCancel}>
                      <img alt="example" style={{ width: '100%' }} src={previewImage} />
                    </Modal>
                  </div>
                </div>
              </Content>
              <Sider width='450' className={style.sider}>
                <div className={style.gosubmit} onClick={this.release}>发布</div>
                <div className={style.contentlist03}>
                  <span>选择栏目：</span>
                  <Cascader value={this.state.sectionarr} fieldNames={{value:'name'}} onChange={this.cascaderChange} options={this.state.lanmu_options} placeholder="选择栏目" />
                </div>
                <div className={style.contentlist02}>
                  <span>列表图：</span>
                  <div className={style.list_img}>
                  <Upload
                    listType="picture-card"
                    className="avatar-uploader"
                    showUploadList={false}
                    action="/upload"
                    onChange={this.imghandleChange}
                  >
                    {listimgurl ? <img src={listimgurl} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
                  </Upload>
                  </div>
                </div>
                <div className={style.contentlist03}>
                  <span>发布时间：</span>
                  <DatePicker mode={this.state.DatePickerMod} showTime value={this.state.updatatime!=''?moment(this.state.updatatime,"YYYYMMDD HHmmss"):null} onChange={this.datechange} onOpenChange={this.handleOpenChange} onPanelChange={this.handlePanelChange}/>
                </div>
                <div className={style.contentlist03}>
                  <span>排序：</span>
                  <Input value={this.state.orders} onChange={this.orderChange} placeholder='请输入排序' />
                </div>
                <div className={style.contentlist03}>
                  <span>状态：</span>
                  <Radio.Group showTime onChange={this.statusChange} value={this.state.ifdisplay}>
                    <Radio value={'1'}>显示</Radio>
                    <Radio value={'0'}>隐藏</Radio>
                  </Radio.Group>
                </div>
              </Sider>
            </Layout>
          </div>
          <div style={this.state.header_idx == 1?{display:'block'}:{display:'none'}} className={style.seo}>
            <div className={style.contentlist04}>
              <span>自定义页面title：</span>
              <Input placeholder='输入页面title'/>
            </div>
            <div className={style.contentlist04}>
              <span>关键词：</span>
              <Input placeholder='输入关键词'/>
            </div>
            <div className={style.contentlist04}>
              <span>描述文字：</span>
              <TextArea placeholder='输入描述文字' />
            </div>
          </div>
        </div>
      </div>
    );
  }
}
 
export default Modify;